<template>
  <section>
    <el-card class="search-card">
      <BasicTableForm ref="formData"
        isScalingBtn
        :colNumOfRow="4"
        formItemWidth="120px"
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm" />
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :showSelectCol="true"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :tableHeight="460"
        :actionColWidth="460"
        :selection-change="selectionChange"
        :check-selectable="checkSelectable"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div slot="content_context">
          <el-button
            v-if="showBtn('导出') && supplierExportConfig.supplier"
            :disabled="!pagination.total"
            size="mini"
            type="primary"
            icon="el-icon-download"
            :loading="exportLoading"
            @click="handleExportFile"
            >导出</el-button>
          <el-button
            v-if="showBtn('新增')"
            size="mini"
            type="primary"
            @click="handleCreateSupplier"
            >新建潜在供应商</el-button>
          <el-button
            v-if="showBtn('批量交接')"
            size="mini"
            type="primary"
            :disabled="!tableInfo.selection.length"
            @click="handleBatchHandover(tableInfo.selection)"
            >批量交接</el-button>
          <el-button
            size="mini"
            type="primary"
            class="right-btn"
            @click="handleConfigTableColumns"
            >字段显示设置</el-button>
        </div>
      </basic-table>
    </el-card>
    <ConvertSupplierDialog
      ref="convertSupplierDialog"
      :convertType="convertType"
      :supplier="supplier"
      :dialogVisible="dialogVisible"
      @handleSubmit="handleDialogSubmit"
      @handleClose="handleDialogClose" />
    <ConfigTableColumnsDialog
      :menuId="menuId"
      v-if="fieldSettingVisible"
      :dialogVisible="fieldSettingVisible"
      @handleClose="handleConfigTableColumnsDialogClose"
      @handleSubmit="hanldSubmitTableColumnsConfig" />
  </section>
</template>

<script>
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
import BasicTableForm from '@/components/supplier/BasicForm'; // 表单组件
import BasicTable from '@/components/supplier/BasicTable';
import ConfigTableColumnsDialog from '@/pages/supplier/components/configTableColumnsDialog';
import ConvertSupplierDialog from '@/pages/supplier/components/convertSupplierDialog'; // 转化弹窗
import { demoteSupplier } from '@/api/supplier/management/common';
import {
  queryPotentialSupplierListService,
  exportPotentialSupplierFileService
} from '@/api/supplier/management/potentialSupplier';
import {
  getListColumnSettings,
  supplierPreConvertCheck,
} from '@/api/supplier/components'
import {
  renewContractService,
  singleContractService,
} from '@/api/supplier/management/supplierContract';
import BasicPage from '@/mixins/supplier/basicPage';
import Dict from '@/mixins/supplier/dict';
import ManageArea from '@/mixins/supplier/manageArea';
import { createExcelByExport, handleOpenNewPage } from '@/utils/bizUtils';
import { isResponseSuccess, getHasIndexTableData } from '@/pages/supplier/utils/bizUtils';
import { INITIAL_FIELDS_VALUE, FORM_ITEM_LIST } from './constants';
import Setting from '@/setting'
const menuId = 330

export default {
  mixins: [Dict, ManageArea, BasicPage],
  components: {
    BasicTableForm,
    BasicTable,
    ConvertSupplierDialog,
    ConfigTableColumnsDialog,
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  data () {
    return {
      menuId,
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        selection: [],
        columns: [],
        loading: false
      },
      pagination: {
        current: 1,
        total: 0,
        size: 10
      },
      formData: Object.assign({}, INITIAL_FIELDS_VALUE),
      // toolbarConfig: {
      //   slots: {
      //     // 自定义工具栏模板
      //     buttons: 'toolbar_buttons',
      //     tools: 'toolbar_tools'
      //   }
      // },
      convertType: '3',
      dialogVisible: false,
      fieldSettingVisible: false,
      supplier: {},
    };
  },
  created () {
    this.getColSettings();
    this.getTableData();
  },
  methods: {
    // 获取列表配置
    async getColSettings () {
      const { status, message, result = [] } = await getListColumnSettings({ menuId })
      if (status === '0') {
        this.setTableColumns(result)
      } else {
        this.$message.error(message)
      }
    },
    // 应用列表配置
    setTableColumns (data) {
      // const indexCol = { title: '序号', key: 'index', width: 50 }
      const arr = data.filter(i => i.isShow).map(i => {
        return {
          title: i.label,
          key: i.prop,
          width: i.width
        }
      })
      // arr.unshift(indexCol)
      this.tableInfo.columns = arr.map((i) => {
        if (i.key === 'supplierName') {
          i.formatter = (row, column, cellValue, index) => {
            return <router-link target="_blank" to={{ name: 'viewPotentialSupplier', query: { id: row.supplierId } }}>{ row.supplierName }</router-link>
          }
        }
        return i
      })
    },
    async handleExportFile () {
      const res = await exportPotentialSupplierFileService(
        this.getRequestParams(),
        state => { this.exportLoading = state }
      )
      if (res) {
        createExcelByExport({ excelTitle: '潜在供应商信息', res })
      }
    },
    handleQueryForm () {
      this.getTableData(1);
    },
    // 勾选需要处理
    selectionChange (rows) {
      this.tableInfo.selection = rows;
    },
    // CheckBox 是否可以勾选
    checkSelectable ({ row }) {
      // console.log('row :>> ', row);
      return true
    },
    // 页码切换
    handlePageChange (val) {
      this.getTableData(val);
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.getTableData(1, val);
    },
    // 获取列表查询参数
    getRequestParams () {
      const {
        supplierCode,
        supplierName,
        mainCategoryId,
        mainProduct,
        manageCategoryId,
        supplierType,
        managementAreaId,
        centralPurchase,
        belongDepartment,
        businessContact,
        coordination,
        createUser,
        reconciliationDate,
        checkoutTime,
        paidType,
        checkoutRange,
        settlementType,
        centralizedSettle,
        centralizedSettlePlace,
        acceptInvoice,
        rebate,
        freightPayer,
        invoiceType,
        accountPhone,
      } = this.formData
      return {
        supplierCode,
        supplierName,
        mainCategoryId,
        mainProduct,
        manageCategoryId,
        supplierType,
        managementAreaId,
        centralPurchase,
        belongDepartment,
        businessContact,
        coordination,
        createUser,
        reconciliationDate,
        checkoutTime,
        paidType,
        checkoutRange,
        settlementType,
        centralizedSettle,
        centralizedSettlePlace,
        acceptInvoice,
        rebate,
        freightPayer,
        invoiceType,
        accountPhone,
      }
    },
    async getTableData (current = this.pagination.current, size = this.pagination.size) {
      sessionStorage.setItem('buttonId', getBtnsId('查询'));
      const params = Object.assign({ current, size }, this.getRequestParams())
      const resp = await queryPotentialSupplierListService(params, state => { this.tableInfo.loading = state })
      if (resp && resp.result) {
        const { records, total, pages } = resp.result
        this.pagination = Object.assign(this.pagination, { current, size, total, pages })
        this.tableInfo.list = getHasIndexTableData(records, this.pagination)
      } else {
        this.tableInfo.list = []
      }
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      return <div>
        <el-button type="text"
          disabled={!this.showBtn('编辑')}
          nativeOnClick={() => { this.handlePermissionCheck(row, () => { this.handleEdit(row) }) }}
        >编辑</el-button>
        {row.signContract === 1 ? <el-popconfirm
          confirm-button-text='签订长协合同'
          cancel-button-text='签订单笔合同'
          cancel-button-type='primary'
          icon="el-icon-info"
          title="请选择签订合同类型："
          onConfirm={() => { this.handleSignContract(row, 0) }}
          onCancel={() => { this.handleSignContract(row, 1) }}
        >
          <el-button type="text" disabled={!this.showBtn('签订合同')} slot="reference" style="margin: 0 10px">签订合同</el-button>
        </el-popconfirm> : null}
        <el-button type="text"
          disabled={!this.showBtn('转为合格')}
          nativeOnClick={() => { this.handlePermissionCheck(row, () => { this.handleConvertSuppliers(row, 'qualified') }) }}
        >转为合格</el-button>
        <el-button type="text"
          disabled={!this.showBtn('转为线索')}
          nativeOnClick={() => { this.handlePermissionCheck(row, () => { this.handleConvertSuppliers(row, 'clues') }) }}
        >转为线索</el-button>
        <el-button type="text"
          disabled={!this.showBtn('淘汰供应商')}
          nativeOnClick={() => { this.handlePermissionCheck(row, () => { this.handleEliminateSuppliers(row) }) }}
        >淘汰供应商</el-button>
        <el-button type="text"
          disabled={!this.showBtn('交接业务对接人')}
          nativeOnClick={() => { this.handlePermissionCheck(row, () => { this.handleBatchHandover(row) }) }}
        >交接业务对接人</el-button>
        <el-button type="text" nativeOnClick={() => { this.handleViewApprovalLog(row) }}>审批日志</el-button>
      </div>
    },
    // 新建潜在供应商
    handleCreateSupplier () {
      // this.$router.push({ name: 'addPotentialSupplier' });
      handleOpenNewPage(this, { name: 'addPotentialSupplier' })
    },
    // 批量交接业务对接人
    handleBatchHandover (selection) {
      let ids = []
      if (Array.isArray(selection)) {
        ids = selection.map(({ supplierId }) => supplierId)
      } else {
        ids.push(selection.supplierId)
      }
      this.$router.push({ name: 'batchHandover', query: { id: ids } });
    },
    // 列表字段配置
    handleConfigTableColumns () {
      this.fieldSettingVisible = true;
    },
    // 字段显示设置弹窗关闭
    handleConfigTableColumnsDialogClose () {
      console.log('handleConfigTableColumnsDialogClose')
      this.fieldSettingVisible = false;
    },
    // 提交字段显示设置
    hanldSubmitTableColumnsConfig (data) {
      // console.log('hanldSubmitTableColumnsConfig', data)
      this.setTableColumns(data)
      this.fieldSettingVisible = false;
    },
    // 权限校验
    handlePermissionCheck (data, callback) {
      this.queryDataPermissionAction(data.supplierId).then(res => {
        if (res) {
          callback()
        }
      })
    },
    // 编辑
    handleEdit (data) {
      this.$router.push({ name: 'editPotentialSupplier', query: { id: data.supplierId } });
    },
    // 签订合同
    async handleSignContract (data, singleFlag) {
      if (this.contractLoading) {
        return
      }
      const tag = await this.queryDataPermissionAction(data.supplierId)
      if (!tag) {
        return;
      }
      const { supplierId } = data
      const operateType = 1
      try {
        this.contractLoading = true
        let res;
        if (singleFlag) {
          res = await singleContractService({ supplierId, operateType, singleFlag });
        } else {
          res = await renewContractService({ supplierId, operateType, singleFlag });
        }
        this.contractLoading = false
        if (isResponseSuccess(res)) {
          const contractUrl = `${Setting.SUPPLIER_CONTRACT_HOST}${res.result.url}`
          window.open(contractUrl);
        }
      } catch (err) {
        this.contractLoading = false
      }
    },
    // 转化供应商
    async handleConvertSuppliers (data, type) {
      console.log('data: ', data)
      console.log('type: ', type)
      const { supplierId } = data
      console.log('潜在转合格供应商 operateType:>> ', 5);
      const { result } = await supplierPreConvertCheck({ supplierId, operateType: 5 })
      if (result === '1') {
        if (type === 'qualified') {
          this.$router.push({ name: 'corventPotential2Qualified', query: { id: supplierId } });
        } else {
          // 潜在转线索
          this.convertType = '3'
          this.supplier = data
          this.dialogVisible = true
        }
      } else {
        this.$message.error(result)
      }
    },
    // 淘汰供应商
    handleEliminateSuppliers (data) {
      console.log(data)
      this.convertType = '10'
      this.supplier = data
      this.dialogVisible = true
    },
    // 关闭转化供应商弹窗
    handleDialogSubmit (data) {
      if (this.convertType === '3' && data) {
        // 潜在降级线索
        const { causeType, causeDescription, supplierId, supplierCode, supplierName } = data
        const supplierBill = { causeType, causeDescription, supplierId, supplierCode, supplierName, supplierClassify: 40899 }
        const obj = { processDocumentOperateType: 9, processDocumentStatus: 10, supplierBill }
        demoteSupplier(obj).then((resp) => {
          if (resp && resp.status === '0') {
            this.$refs.convertSupplierDialog.close()
            this.$message.success('操作成功！')
          }
        }).finally(() => {
          this.$refs.convertSupplierDialog.updateLoadingState()
        })
        return
      }
      this.dialogVisible = false
    },
    handleDialogClose () {
      this.dialogVisible = false
    },
    // 审批日志
    handleViewApprovalLog (data) {
      console.log(data)
      this.$router.push({ name: 'auditLog', query: { supplierId: data.supplierId, isPotential: 1, module: 1 } });
    },
  }
}
</script>

<style lang="less" scope>
.right-btn {
  float: right;
}
</style>
